import base64
import os

from flask import Flask, render_template, make_response
from flask import redirect, request, url_for

app = Flask(__name__)


@app.route('/', methods=['POST', 'GET'])
def index():
    if request.method == 'POST':
        # 获取表单提交的参数
        username = request.form.get('username')
        password = request.form.get('password')

        if not all([username, password]):
            print('参数不足')

        print(username, password)
        if username == 'laowang' and password == '1234':
            # 状态保持,设置用户名到cookie中表示登录成功
            response = redirect(url_for('transfer'))
            # 这里只保存了账号
            response.set_cookie('username', username)
            return response
        else:
            print('账号或密码错误')

    return render_template('temp_login.html')


@app.route('/transfer', methods=['POST', 'GET'])
def transfer():
    username = request.cookies.get('username', None)
    if not username:
        return redirect(url_for('index'))

    if request.method == 'POST':
        to_account = request.form.get('to_account')
        money = request.form.get('money')


        # 提取form表单携带的csrf_token
        form_csrf_token = request.form.get('csrf_token')
        # 获取cookie中携带的csrf_token
        cookie_csrf_token = request.cookies.get('csrf_token')
        # 校验
        if form_csrf_token != cookie_csrf_token:
            return "非法请求"


        print('假装执行转账操作,将当前登录用户的钱转账到指到账户')
        return '转账 %s 元到 %s 成' % (money, to_account)

    # 生成 csrf_token 的值
    csrf_token = generate_csrf()
    # 往模板中设置csrf_token随机值
    response = make_response(render_template('temp_transfer.html', csrf_token=csrf_token))
    # 往cookie中设置csrf_token随机值
    response.set_cookie("csrf_token", csrf_token)

    return response

# 定义函数生成 csrf_token
def generate_csrf():
    # 生成一个48位的随机字符串 作为csrf_token的值
    return bytes.decode(base64.b64encode(os.urandom(48)))


if __name__ == '__main__':
    app.run(debug=True, port=9000)
